<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head th:include="head :: htmlhead" th:with="title='协议生成管理'">
</head>

<body>

<!--<form class="layui-form" action="">-->

<input id="version" th:value="${version}"  hidden="true">
<input id="id" th:value="${id}"  hidden="true">
<input id="allTypes" th:value="${allTypes}"  hidden="true">

	<h1 align="center" style="color:#FF5722"  th:text="'当前使用的版本为'+${version}"> </h1>
<a th:href="'/zproto/module/viewModule?version='+${version}"><p align="center">回到模块页</p>
</a>

<protocolTmp id="protocolTmp" hidden="true">
<hr class="layui-border-black">
<div class="layui-form-item">

	<div th:if="${sortBy==3}" class="layui-inline">
		<label class="layui-form-label">内部序号：</label>
		<div class="layui-input-inline" style="width: 75px;">
			<input type="tel" name="protocol_insideId" autocomplete="off"
				   class="layui-input">
		</div>
	</div>

	<div class="layui-inline">
		<label class="layui-form-label">协议类名：</label>
		<div class="layui-input-inline">
			<input type="text" name="protocol_name" autocomplete="off"
				class="layui-input">
		</div>
	</div>
	<div class="layui-inline">
		<label class="layui-form-label">协议注释</label>
		<div class="layui-input-inline">
			<input type="text" name="protocol_comment" autocomplete="off"
				class="layui-input">
		</div>
	</div>
<!-- 	<button onclick="$(this).parent().parent().remove();" class="layui-btn">删除协议</button> -->
	 <button type="button" class="layui-btn layui-btn-sm" onclick="$(this).parent().parent().remove();">
	    <i class="layui-icon">&#xe640;</i>
	  </button>
	<br>
	<br>
	<br>
	<div name="fields"></div>
	<button name="addField" class="layui-btn">添加字段</button>
</div>
</protocolTmp>

<fieldTmp id="fieldTmp" hidden="true">
<div class="layui-form-item">
	<div class="layui-inline layui-form">
		<label class="layui-form-label">列表:</label>
		<div class="layui-input-block">
		<input type="checkbox" name="field_repeated" lay-skin="switch" lay-text="true|false">
		</div>
	</div>
	
	<div class="layui-inline">
		<label class="layui-form-label">字段类型：</label>
		<div class="layui-input-inline layui-form">
		<input type="text" name="fieldType" id="fieldType" lay-filter="fieldType" class="layui-input" placeholder="请选择"
			   style="position:absolute;z-index:2;width: 80%;" lay-verify="required" value="" autocomplete="off">
		<select name="field_type" id="field_type"  lay-search autocomplete="off" lay-filter="field_type">
			<option value=""></option>
			<option th:each="prototype:${allTypes}" th:value="${prototype}" th:text="${prototype}"></option>
		</select>
		</div>
	</div>
	
	<div class="layui-inline">
		<label class="layui-form-label">字段名：</label>
		<div class="layui-input-inline">
			<input type="text" name="field_name" autocomplete="off" class="layui-input">
		</div>
	</div>
	<div class="layui-inline">
		<label class="layui-form-label">注释：</label>
		<div class="layui-input-inline">
			<input type="text" name="field_comment" autocomplete="off" class="layui-input">
		</div>
	</div>
<!-- 	<button onclick="$(this).parent().parent().remove();" class="layui-btn">删除字段</button> -->
	 <button type="button" class="layui-btn layui-btn-sm" onclick="$(this).parent().parent().remove();">
	    <i class="layui-icon">&#xe640;</i>
	  </button>
</div>
</fieldTmp>

<br>
<div id="content"></div>
<hr class="layui-border-red">

<button id="addProtocol" class="layui-btn">添加协议</button>
<button id='submit' class="layui-btn">提交</button>
<button id="createMessage1" name="csharp" class="layui-btn" value="csharp" >生成csharp协议</button>
<button id="createMessage2" name="java" class="layui-btn" value="java" >生成Java协议</button>

<br>
<br>
<br>
<br>
<!--</form>-->
</body>
<script type="text/javascript">

    layui.use('layer', function(){
        var layer = layui.layer;
		var form = layui.form;
		form.on('select(field_type)', function(data){
			// console.log(data.elem); //得到select原始DOM对象
			// console.log(data.value); //得到被选中的值
			// console.log(data.othis); //得到美化后的DOM对象
			var eleId = data.elem.id;
			var eleIndex = eleId.replace("field_type", "");
			$("#fieldType"+eleIndex).val(data.value); //这里直接将obj的值设置给input框达到选择input时让它俩联动起来
		});

    });

    $("#addProtocol").click(function(){
        var clone = $("#protocolTmp").clone(true);
        clone.attr("hidden",false);
        clone.attr("name","protocol");
        $("#content").append(clone);
        layui.use('form', function(){
            form = layui.form;
            form.render('checkbox');
        });
    });

    $("button[name='addField']").click(function(){
        var clone = $("#fieldTmp").clone(true);
        clone.attr("hidden",false)
		eleIndex ++;
		clone.find("input[name='fieldType']").attr("id", "fieldType"+eleIndex);
		clone.find("select[name='field_type']").attr("id", "field_type"+eleIndex);

        $(this).parent().find("div[name='fields']").append(clone);
        layui.use('form', function(){
            form = layui.form;
            form.render('checkbox');
            form.render('select');
        });
    });
    
    $("#submit").click(function(){
        // var moduleId=$("#moduleId").val();
        // var moduleName=$("#moduleName").val();
        // var moduleComment=$("#moduleComment").val();
        var protocolIndex=0;
        
        var protocolArray = [];
        $("protocolTmp[name='protocol']").each(function(){
            var protocol_obj={};
            var fieldIndex=0;
            var fieldArray=[];

            protocol_obj.insideId=$(this).find("input[name='protocol_insideId']").val();
            protocol_obj.name=$(this).find("input[name='protocol_name']").val();
            protocol_obj.comment=$(this).find("input[name='protocol_comment']").val();

            $(this).find("#fieldTmp").each(function(){
                var field_obj={};
                var index=fieldIndex+1;
                field_obj.index=index;
                field_obj.repeated=$(this).find("input[name='field_repeated']:checked").val()==="on";
                //field_obj.type=$(this).find("select[name='field_type'] option:selected").val();
				field_obj.type=$(this).find("input[name='fieldType']").val();
                field_obj.name=$(this).find("input[name='field_name']").val();
                field_obj.comment=$(this).find("input[name='field_comment']").val();
                fieldArray[fieldIndex]=field_obj;
                fieldIndex++;
            });
            protocol_obj.fields=fieldArray;
            protocolArray[protocolIndex]=protocol_obj;
            protocolIndex++;
        });
		var version=$("#version").val();
		var id=$("#id").val();
        $.ajax({
            type: 'POST',
            url: '/zproto/module/protoCommit?version='+version+'&id='+id,
            data: JSON.stringify(protocolArray),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function(data){
            	if(data.code == 0){
            		 layer.alert("提交成功！")
            	}else{
            		layer.alert(data.tips)
            	}
            },
            error: function(jqXHR){console.log(jqXHR)},
        });
    });

    // //input和select添加联动
	// //设置select 与 input 输入框联动
	// //form.on('select(field_type)',function (obj) {
	// //$("#field_type").on('change',function () {
	// $("#field_type").change(function () {
	// 	//obj有 每一个option的值，有兴趣的可以再次打印然后看obj的结构
	// 	var obj =$("#field_type").val()
	// 	console.log("===="+obj)
	// 	$("#fieldType").val(obj.value); //这里直接将obj的值设置给input框达到选择input时让它俩联动起来
	// 	$("#field_type").next().find("dl").css({"display":"note"});
	// 	form.render();
	// })

	//给input框加监听
	$("#fieldType").on('input',function () {
		//这里是获取input输入的值设置给select 这里的select 一定要添加一个 lay-search 这个属性，否则select 不可搜索
		var eleId = document.activeElement.id;
		var eleIndex = eleId.replace("fieldType", "");
		var value = $("#fieldType"+eleIndex).val()
		console.log("===value===>"+value)
		value = value.replace(/^\s*/,"");//利用正则去除左侧空格
		$("#field_type"+eleIndex).val(value);
		form.render();
		$("#field_type"+eleIndex).next().find(".layui-select-title input").click();
		var dl = $("#field_type"+eleIndex).next().find("dl").children();
		var j = -1;
		for (var i =0;i<dl.length;i++){
			if (dl[i].innerHTML.indexOf(value)<=-1){
				dl[i].style.display="none";
				j++
			}
			if (j ==dl.length-1){
				$("#field_type"+eleIndex).next().find("dl").css({"display":"none"});
			}
		}
	})

	// $(document).on('click','input.layui-input',function(){
	// 		var parEle = document.activeElement.parentElement.parentElement.parentElement;
	// 		var curActiveId = parEle.getElementsByTagName("select")[0].id;
	// 		console.log(curActiveId);
	// })

	// function aa(){
	// 	var activename=document.activeElement.name; // 当前获取焦点的对象
	// 	alert(activename);
	// }
	//
	// //联通下拉菜单和输入框
	// $(document).on('click','div.layui-form-select',function(){
	// 	    var parEle = document.activeElement.parentElement.parentElement.parentElement;
	// 	    var curActiveId = parEle.getElementsByTagName("select")[0].id;
	// 		console.log(curActiveId);
	// })



	$("#createMessage1").click(function(){
		var version=$("#version").val();
		var id=$("#id").val();
		var langType=$("#createMessage1").val();
		$.ajax({
			type: 'GET',
			url: '/zproto/module/createMessage',
			dataType:"json", //返回格式为json
			data:{"id":id,"version":version,"langType":langType}, //参数值
			contentType: 'application/x-www-form-urlencoded',
			success: function(data){
				if(data.code==0){
					layer.alert("生成成功！");
				}else{
					layer.alert("生成失败!");
				}
			},
			error: function(jqXHR){console.log(jqXHR)},
		});
	});
	
	$("#createMessage2").click(function(){
		var version=$("#version").val();
		var id=$("#id").val();
		var langType=$("#createMessage2").val();
		$.ajax({
			type: 'GET',
			url: '/zproto/module/createMessage',
			dataType:"json", //返回格式为json
			data:{"id":id,"version":version,"langType":langType}, //参数值
			contentType: 'application/x-www-form-urlencoded',
			success: function(data){
				if(data.code==0){
					layer.alert("生成成功！");
				}else{
					layer.alert("生成失败!");
				}
			},
			error: function(jqXHR){console.log(jqXHR)},
		});
	});
</script>


<script th:inline="javascript">
	var eleIndex = 0;
    $(document).ready(function(){
 		var protocols = /*[[${data}]]*/ ;
 		var allTypes = /*[[${allTypes}]]*/ ;
        for(var i in protocols){
            var protocol=protocols[i];
            var clone = $("#protocolTmp").clone(true);
            clone.attr("hidden",false);
            clone.attr("name","protocol");
			clone.find("input[name='protocol_insideId']").val(protocol.insideId);
            clone.find("input[name='protocol_name']").val(protocol.name);
            clone.find("input[name='protocol_comment']").val(protocol.comment);

            var fields=protocol.fields;
            for(var j in fields){
				eleIndex ++;
                var fieldClone = $("#fieldTmp").clone(true);
                fieldClone.attr("hidden",false);
                var field=fields[j];
                fieldClone.find("input[name='field_repeated']").prop("checked",field.repeated);

				fieldClone.find("input[name='fieldType']").attr("id", "fieldType"+eleIndex);
				fieldClone.find("input[name='fieldType']").val(field.type);

				fieldClone.find("select[name='field_type']").attr("id", "field_type"+eleIndex);
                fieldClone.find("select[name='field_type']").val(field.type);

                fieldClone.find("input[name='field_name']").val(field.name);
                fieldClone.find("input[name='field_comment']").val(field.comment);
                clone.find("div[name='fields']").append(fieldClone);
            }
            $("#content").append(clone);
        }
        layui.use('form', function(){
            form = layui.form;
            form.render('checkbox');
            form.render('select');
        });
    });

</script>

</html>